package com.boomkeeper.excel.rw;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.boomkeeper.archive.model.ArchiveDirctory;
import com.boomkeeper.core.model.ChangeOrder;
import com.boomkeeper.core.utils.DateUtils;
import com.boomkeeper.excel.utils.ExcelUtils;

/**
 * 读取所有变更单的Excel文件并汇总
 * @author Boomkeeper
 *
 */
@Component
public class Reader {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(Reader.class);
	
	@Autowired
	private ArchiveDirctory archiveDirctory;
	
	private List<ChangeOrder> changeOrderList = new ArrayList<>();
	
	public Reader readFils() {
		File[] excelFiles = new File(archiveDirctory.getLteVersionChangeOrderPath()).listFiles();
		for (File file : excelFiles) {
			this.readFile(file);
		}
		
		return this;
	}
	
	public void readFile(File excelFile) {
		if (excelFile.canRead()) {
			try {
				this.readFile(WorkbookFactory.create(excelFile), excelFile.getName());
			} catch (EncryptedDocumentException | InvalidFormatException | IOException e) {
				LOGGER.error("创建excel reader时发生异常", e);
			}
		} else {
			LOGGER.error("excel不可读", excelFile.getAbsolutePath());
		}
	}
	
	public void readFile(Workbook workbook, String fileName) {
		ChangeOrder changeOrder = new ChangeOrder();
		Sheet sheet = workbook.getSheetAt(0);
		Row row = sheet.getRow(1);
		changeOrder.setAuthor(row.getCell(1).getStringCellValue());
		changeOrder.setDate(DateUtils.parseDateString(row.getCell(8).getDateCellValue()));
		changeOrder.setBug(ExcelUtils.isBug(sheet));
		changeOrder.setRedmine(ExcelUtils.getRedmine(sheet));
		changeOrder.setSubject(sheet.getRow(7).getCell(1).getStringCellValue());
		changeOrder.setDesc(sheet.getRow(7).getCell(1).getStringCellValue());//图省事...
		changeOrder.setChangeOrderFileName(fileName);
		
		this.changeOrderList.add(changeOrder);
	}
	
	public List<ChangeOrder> getData(){
		return this.changeOrderList;
	}
	
//	public List<ChangeOrder> getData(ChangeOrderData changeOrderData){
//		changeOrderData.setChangeOrderList(this.changeOrderList);
//		return this.changeOrderList;
//	}
}
